<template>
  <div class="app-container">
    <el-button
      v-if="!show"
      class="collapesbutton"
      type="primary"
      plain
      style="left: 0; top: 100px; height: 10%"
      @click="show = !show"
    >
      <i class="el-icon-d-arrow-right"></i>
    </el-button>
    <section style="height: 100%; margin: 0; width: 100%">
      <div
        v-show="show"
        class="treeMenu"
        style="width: calc(15% - 6px); float: left"
      >
        <el-button
          class="collapesbutton"
          type="primary"
          plain
          style="right: 1px; top: 50px; height: 10%"
          @click="show = !show"
        >
          <i class="el-icon-d-arrow-left"></i>
        </el-button>
        <div class="head-container" style="border-right: 1px solid #dcdfe6">
          <el-input
            v-model="keyword"
            placeholder="请输入关键字"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin: 10px 0; width: 100%; hegith: 80%"
          />
        </div>
        <el-menu :default-active="activeIndex" class="el-menu-vertical">
          <el-menu-item
            v-for="(item, i) in showMenuData"
            :key="i"
            :index="i.toString()"
            @click="handleOpen(item, i.toString())"
          >
            <i :class="item.icon"></i>
            <span slot="title" v-html="item.name" :title="item.name"> </span>
            <i
              class="el-icon-delete"
              style="font-size: 14px"
              @click="
                handleDelete('/' + $route.path.replace('/outer','').split('/')[1], '删除', item)
              "
            >
            </i>
          </el-menu-item>
        </el-menu>
      </div>
      <resize-bar v-show="show" />
      <div
        style="
          min-width: 75%;
          max-width: 95%;
          padding: 10px 10px 0;
          height: 100%;
          width: 85%;
          float: right;
          box-sizing: border-box;
        "
        :class="show ? '' : 'max-size'"
      >
        <div class="mainContent">
          <div class="manage-header">
            <el-form
              :inline="true"
              :model="queryParams"
              ref="queryForm"
              label-width="auto"
              @submit.native.prevent
            >
              <el-form-item
                v-if="
                  searchFormData.length != 0 && searchFormData[0].status === '1'
                "
                :key="searchFormData[0].prop"
                :label="searchFormData[0].name"
              >
                <el-input
                  size="small"
                  v-model="queryParams[searchFormData[0].prop]"
                  :placeholder="'请输入' + searchFormData[0].name"
                >
                </el-input>
              </el-form-item>
              <el-form-item v-if="searchFormData.length != 0">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  v-preventReClick
                  @click="handleQuery"
                  >搜索
                </el-button>
                <el-button
                  type="info"
                  icon="el-icon-refresh"
                  size="mini"
                  v-preventReClick
                  @click="resetQuery"
                  >重置
                </el-button>
                <el-button
                  v-if="searchFormData.length > 1"
                  icon="el-icon-arrow-down"
                  size="mini"
                  id="more-attr"
                  v-preventReClick
                  @click="moreattr"
                  >更多属性
                </el-button>
              </el-form-item>
              <div id="more-list" style="display: none">
                <div></div>
                <el-form-item
                  v-for="item in searchFormData.slice(1)"
                  :key="item.prop"
                  :label="item.name"
                >
                  <div v-if="item.status === '1'">
                    <!--根据type来显示是什么标签-->
                    <el-select
                      v-model="queryParams[item.prop]"
                      placeholder="请选择"
                      v-if="item.componentType === 'el-select'"
                    >
                      <el-option
                        v-for="item in item.optionValue"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                    <el-date-picker
                      v-model="queryParams[item.prop]"
                      size="small"
                      style="width: 240px"
                      value-format="yyyy-MM-dd"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      v-if="item.componentType === 'el-date-picker'"
                    ></el-date-picker>
                    <el-input
                      size="small"
                      v-model="queryParams[item.prop]"
                      :placeholder="'请输入' + item.name"
                      v-else
                    >
                    </el-input>
                  </div>
                </el-form-item>
              </div>
            </el-form>
          </div>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <div
                v-for="(toolbar, index) in toolbarData"
                :key="index"
                style="display: inline-block"
              >
                <template
                  v-if="
                    (toolbar.info.display == 0 && toolbar.data.length >= 4) ||
                    toolbar.info.display == 2
                  "
                >
                  <el-dropdown
                    style="padding: 0; margin-right: 10px; margin-left: 10px"
                  >
                    <el-button type="primary" size="mini">
                      <i :class="toolbar.info.icon"></i>
                      {{ toolbar.info.description }}
                      <i class="el-icon-arrow-down"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <div v-for="(btn, key) in toolbar.data" :key="key">
                        <el-dropdown-item
                          v-if="btn.status === '1' && btn.location === '2'"
                        >
                          <el-button
                            size="mini"
                            type="text"
                            :icon="btn.icon"
                            v-preventReClick
                            @click="clickEvent(btn)"
                            >{{ btn.name }}</el-button
                          >
                        </el-dropdown-item>
                      </div>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
                <template
                  v-if="
                    (toolbar.info.display == 0 && toolbar.data.length < 4) ||
                    toolbar.info.display == 1
                  "
                >
                  <div
                    v-for="(btn, index) in toolbar.data"
                    :key="index"
                    style="display: inline-block; margin: 0 3px"
                  >
                    <template v-if="btn.name == '全编辑'">
                      <el-button
                        v-if="!editall"
                        :type="btn.styleType"
                        :icon="btn.icon"
                        size="mini"
                        @click="clickEvent(btn)"
                        >{{ btn.name }}
                      </el-button>
                      <el-button
                        type="primary"
                        size="mini"
                        @click="subEditAll()"
                        v-if="editall"
                        >保存</el-button
                      >
                      <el-button
                        type="info"
                        size="mini"
                        @click="cancelEditAll()"
                        v-if="editall"
                        >取消</el-button
                      >
                    </template>
                    <template v-else>
                      <el-button
                        v-if="btn.status === '1' && btn.location === '2'"
                        :type="btn.styleType"
                        :icon="btn.icon"
                        size="mini"
                        v-preventReClick
                        @click="clickEvent(btn)"
                        >{{ btn.name }}
                      </el-button>
                    </template>
                  </div>
                </template>
              </div>
            </el-col>
            <el-popover
              v-if="tableData.length > 0"
              title="列筛选"
              trigger="click"
              style="float: right; margin-right: 10px"
            >
              <el-checkbox
                style="display: block"
                v-for="(item, index) in tableData"
                :key="index"
                :label="item.name"
                v-model="item.show"
                >{{ item.name }}
              </el-checkbox>
              <el-button size="small" slot="reference">
                <i class="el-icon-arrow-down el-icon-menu"></i>
              </el-button>
            </el-popover>
          </el-row>
          <template v-if="tableData.length > 0">
            <!--列表数据-->
            <dynamic-table
              ref="dyTable"
              :list="list"
              @updateList="getList"
              @handleSelectionChange="handleSelectionChange"
              :options="options"
              @editChanged="editChanged($event)"
              :columns="tableData"
              :operates="operates"
              :diff="120"
            >
            </dynamic-table>
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </template>
        </div>
      </div>
      <!-- 添加或修改对话框 -->
      <el-dialog
        ref="addForm"
        :title="title"
        :visible.sync="open"
        v-if="open"
        width="50%"
        v-dialogDrag
        :close-on-click-modal="false"
      >
        <dynamic-form
          :addform="addFormData"
          :form="form"
          :rules="rules"
          :addurl="addurl"
          v-on:openChanged="openChanged($event)"
        >
        </dynamic-form>
      </el-dialog>
      <!-- 添加或修改对话框 -->

      <!-- 添加已存在对话框 -->
      <el-dialog
        ref="formTabel"
        :title="title"
        :visible.sync="topen"
        v-if="topen"
        width="50%"
        v-dialogDrag
        :close-on-click-modal="false"
      >
        <dynamic-form-table
          :exsitId="exsitId"
          :geturl="geturl"
          :submiturl="addurl"
          v-on:topenChanged="topenChanged($event)"
          :table="table"
          :form="form"
        >
        </dynamic-form-table>
      </el-dialog>
      <!-- 添加已存在对话框 -->
    </section>
  </div>
</template>
<script>
import dynamicSearchForm from "@/views/components/dynamicSearchForm";
import dynamicTable from "@/views/components/dynamicTable";
import dynamicForm from "@/views/components/dynamicForm";
import {
  baseRequest,
  getDataList,
  getConfigInfo,
  getData,
  getAddForm,
  delData,
  exportData,
} from "@/api/dynamic/dynamic";
import dynamicTree from "../../components/dynamicTree.vue";
import dynamicFormTable from "@/views/components/dynamicFormTable";
import ResizeBar from '../../components/resizeBar.vue';

export default {
  components: {
    dynamicSearchForm,
    dynamicForm,
    dynamicTable,
    dynamicTree,
    dynamicFormTable,
    resizeBar: () => import("@/views/components/resizeBar"),
  },
  data() {
    return {
      activeName: "menuData",
      activeIndex: "0",
      // 遮罩层
      // 加载层信息
      loading: [],
      // 选中数组
      ids: [],
      selected: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      topen: false,
      show: true,
      closeOnClickModal: false,
      pageTitle: "",
      options: {
        // table 的参数
        stripe: true, // 是否为斑马纹 table
        loading: false, // 是否添加表格loading加载动画
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        mutiSelect: true, // 是否支持列表项选中功能
      },
      keyword: "",
      params: {},
      toolbarData: [],
      searchFormData: [],
      tableData: [],
      menuData: [],
      showMenuData: [],
      treeData: [],
      commandData: [],
      list: [],
      checkedColumns: [],
      columns: [], // 需要展示的列
      operates: {
        // 列操作按钮
        width: 150,
        list: [],
      },
      queryConfigParams: {},
      queryTreeParams: {},
      fileUrl: undefined,
      totypeid: "",
      toid: "",
      queryParams: {
        pageNum: 1,
        pageSize: 30,
      },
      form: {},
      rules: {},
      addFormData: [],
      addurl: "",
      exsitId: [],
      geturl: "",
      table: "",
    };
  },
  created() {
    this.params = JSON.parse(this.$route.meta.pageParams.replace(/'/g, '"'));
    this.queryConfigParams.table = this.params.table;
    this.queryConfigParams.searchForm = this.params.searchForm;
    this.queryConfigParams.command = this.params.command;
    this.queryConfigParams.toolbar = this.params.toolbar;
    this.getMenuList();
    this.getConfig();
    let temp = sessionStorage.getItem(
      this.$route.path + this.$route.query.type
    );
    this.activeIndex = temp != "undefined" && temp != null ? temp : "0";
  },
  updated() {
    let ele = this.$refs.dyTable || this.$refs.treeTable;
    if (ele) {
      ele.tableresize();
    }
  },
  watch: {
    keyword(val) {
      this.showMenuData = this.menuData.filter((item) => {
        if (!val) {
          this.showMenuData = this.menuData.slice();
          return true;
        }
        if (item.name.indexOf(val) !== -1) {
          return item;
        }
      });
    },
  },
  methods: {
    /** 获取列表数据 */
    getMenuList() {
      this.loading = true;
      getDataList(this.$route.path.replace('/outer','')).then((response) => {
        this.menuData = response.rows;
        this.showMenuData = this.menuData.slice();
        this.handleOpen(this.showMenuData[this.activeIndex], this.activeIndex);
        this.loading = false;
      });
    },
    /** 获取配置信息 */
    getConfig() {
      this.loading = true;
      getConfigInfo(this.queryConfigParams).then((response) => {
        this.tableData = response.data.tableData;
        this.formData = response.data.formData;
        this.operates.list = response.data.commandData;
        this.toolbarData = response.data.toolbarData;
        this.tableData.forEach((item, index) => {
          this.checkedColumns.push(item.name);
        });
        this.loading = false;
      });
    },
    GetUrl(url, item) {
      if (url.indexOf("{") != -1) {
        var substr = url.substring(url.indexOf("{") + 1, url.indexOf("}"));
        var keyStr = url.substring(url.indexOf("?") + 1, url.indexOf("="));
        url = url.substring(0, url.indexOf("?"));
        if (substr.length > 0 && item && keyStr.length > 0) {
          this.queryParams[keyStr] = item[substr];
        }
      }
      return url;
    },
    /** 获取列表数据 */
    getList() {
      this.loading = true;
      getDataList(this.fileUrl, this.queryParams).then((response) => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.selected = selection;
    },
    //查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 30,
      };
      this.handleQuery();
    },
    handleOpen(item, i) {
      sessionStorage.setItem(this.$route.path + this.$route.query.type, i);
      this.activeIndex = i;
      this.queryParams = {
        pageNum: 1,
        pageSize: 30,
      };
      this.toid = "";
      this.toid = item.id;
      this.totypeid = item.typeid;
      this.fileUrl = this.GetUrl(this.params.menuUrl, item);
      this.getList();
    },
    handleClose(key, keyPath) {
      // console.log(key, keyPath);
    },
    clickEvent(obj) {
      if (obj.type === "2") {
        this.$router.push({ path: obj.url });
      } else {
        // let pageParams =eval ("(" + obj.pageParams + ")");
        let pageParams = JSON.parse(obj.pageParams.replace(/'/g, '"'));
        if (pageParams.handle == "handleDelete") {
          this.handleDelete(obj.url, obj.description);
        } else if (pageParams.handle == "handleExport") {
          this.handleExport(obj.url);
        } else if (pageParams.handle == "handleConfirm") {
          this.handleConfirm(
            obj.url,
            pageParams.method,
            obj.description,
            pageParams.condition
          );
        } else if (pageParams.handle == "handleAdd") {
          if (pageParams.type == "table") {
            this.handleAddExited(obj);
          } else {
            this.handleAdd(obj.url, pageParams.addForm, obj.description);
          }
        } else if (pageParams.handle == "handleUpdate") {
          this.handleUpdate(obj.url, pageParams.addForm, obj.description);
        }
      }
    },
    handleConfirm(url, method, title, condition) {
      let jugement = this.jugeCondition(condition, url, title);
      if (jugement.flag) {
        this.$confirm(jugement.info, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            baseRequest(jugement.route, method, {}, {}).then((response) => {
              if (response.code == 200) {
                this.msgSuccess(response.msg);
                this.getMenuList();
                return true;
              } else {
                this.msgError(response.msg);
                return true;
              }
            });
          })
          .catch(() => {
            this.msgInfo("已取消");
          });
      }
    },
    /** 新增按钮操作 */
    handleAdd(url, str, title) {
      this.addurl = url;
      this.form = { toid: this.toid, porjectid: this.porjectid };
      this.getFormData(str);
      this.open = true;
      this.title = title ? title : "新增";
    },
    /**  添加已存在*/
    handleAddExited(obj) {
      let pageParams = eval("(" + obj.pageParams + ")");
      this.addurl = obj.url;
      this.title = obj.description;
      this.table = pageParams.table;
      this.geturl = pageParams.getUrl;
      this.form = { toid: this.toid, totypeid: this.totypeid };
      this.topen = true;
    },
    /** 转换选项数据结构 */
    optionNormalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          value: item.id,
          label: item.description,
          parentId: item.parentid,
        };
      });
      return this.handleTree(data, "value");
    },

    /** 转换选项数据结构 */
    selectNormalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          id: item.dictValue,
          description: item.dictLabel,
        };
      });
      return data;
    },
    /** 修改按钮操作 */
    handleUpdate(url, str, title) {
      if (this.ids.length == 0) {
        this.msgError("不能对没有选中进行此项操作！");
        return false;
      }
      this.addurl = url;
      this.getFormData(str);
      this.form["ids"] = this.ids.join(",");
      this.open = true;
      this.title = title ? title : "编辑";
    },
    /** 删除按钮操作 */
    handleDelete(url, title, item = { id: 0 }) {
      const ids = item.id || this.ids;
      if (url == "/pmsproject") {
        url += "/removegroup";
      }
      this.$confirm(
        `是否确认${title} "${
          item.id
            ? item.name
            : this.selected[0].name ||
              this.selected[0].title ||
              this.selected[0].fileName ||
              this.selected[0].folderName
        }" ${this.ids.length > 1 ? "等" : ""}?`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delData(url, ids);
        })
        .then(() => {
          this.getMenuList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport(url) {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportData(url, queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
    openChanged(val) {
      if (this.subopen) this.subopen = false;
      else this.open = false;
      if (val) this.getMenuList();
    },
    topenChanged(val) {
      if (this.subtopen) this.subtopen = false;
      else this.topen = false;
      if (val) this.getMenuList();
    },
    editChanged(val) {
      this.addurl = val.url;
      this.getFormData(val.str);
      this.form = {};
      getData(val.url, val.id.id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = val.title ? val.title : "编辑";
      });
    },
    //获取表单数据
    getFormData(str) {
      let formData = {};
      let optionData = JSON.parse(sessionStorage.getItem("optionsData"));
      getAddForm({ addForm: str }).then((response) => {
        formData = response.data;
        formData.forEach((item, index) => {
          if (
            item.componentType === "el-select" ||
            item.componentType === "el-radio" ||
            item.componentType === "el-checkbox-group"
          ) {
            if (
              item.prop === "policyid" ||
              item.prop === "stateid" ||
              item.prop === "ownerid"
            ) {
              formData[index].optionValue = optionData[item.optionValue];
            } else {
              if (
                this.tempDicts[item.prop] &&
                this.tempDicts[item.prop].length > 0
              )
                formData[index].optionValue = this.selectNormalizer(
                  deepClone(this.tempDicts[item.prop])
                );
              else
                this.getDicts(item.optionValue).then((response) => {
                  formData[index].optionValue = this.selectNormalizer(
                    response.data
                  );
                });
            }
          }
          if (item.componentType === "el-cascader") {
            let optionarr = item.optionValue.split("?");
            if (optionarr.length > 1) {
              this.optionNormalizer(optionData[optionarr[0]]);
              let typearr = [];
              optionData[optionarr[0]].forEach((titem) => {
                if (titem.value === parseInt(optionarr[1])) {
                  typearr.push(titem);
                  formData[index].optionValue = typearr;
                }
              });
            } else {
              formData[index].optionValue = this.optionNormalizer(
                optionData[item.optionValue]
              );
            }
          }
        });
        this.addFormData = formData;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 0;
  margin: 0;
  position: relative;
}
.collapesbutton {
  width: 14px;
  position: absolute;
  top: 0;
  bottom: 0;
  padding: 0;
  border: none;
  margin: auto 0;
  z-index: 200;
}
.treeMenu {
  background-color: #f8f8f8;
  height: 100%;
  position: relative;
}
.el-menu-item {
  border-bottom: 1px solid #dcdfe6;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.app-container .head-container {
  padding-left: 5px;
  padding-right: 5px;
  border-top: 1px solid #d8d8d8;
  border-bottom: 1px solid #dcdfe6;
}

.el-tabs__item {
  height: 30px;
  line-height: 30px;
}

.page-title {
  background: #fff;
  border: 1px solid #d8d8d8;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
  white-space: nowrap;
  /*margin-bottom: 5px;*/
}

.headerContent {
  float: left;
  padding: 20px 0 10px;
  width: 100%;
}

.extendedHeader {
  display: block;
  line-height: 23px;
  white-space: nowrap;
}

.extendedHeader.name {
  font-size: 16px;
  font-weight: bold;
  font-family: "3dsregular", Arial, Helvetica, sans-serif;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.extendedHeader.content {
  font-size: 13px;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.extendedHeader.fromTitle {
  font-size: 13px;
  width: 150px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.flex {
  display: flex;
}
.el-col-21[data-v-0e4055ba] {
  width: 87.5%;
}
.infinite-list {
  list-style: none;
  padding: 5px;
  margin: 0;
}

.infinite-list-item {
  list-style: none;
  padding: 5px;
  margin: 0;
  background-color: #f8f8f8;
  border-bottom: 1px solid #d8d8d8;
  position: relative;
}

.infinite-list-item.selected {
  list-style: none;
  padding: 5px;
  margin: 0;
  background-color: #fff;
  border-bottom: 1px solid #d8d8d8;
  position: relative;
}

.el-dropdown {
  padding: 10px;
  border-right: 1px solid #c3c3c3;
}

.mainContent {
  float: left;
  width: 100%;
  padding: 0 4px 0 5px;
  height: 100%;
}

.extendedMain {
  display: block;
  line-height: 23px;
  white-space: nowrap;
}

.extendedMain.name {
  font-size: 16px;
  font-weight: bold;
  font-family: "3dsregular", Arial, Helvetica, sans-serif;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.extendedMain.content {
  font-size: 13px;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 5px 0 5px 10px;
}

.extendedMain.fromTitle {
  font-size: 13px;
  width: 150px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 5px 0 5px 10px;
  background-color: #f8f8f8;
}
.el-tree {
  background-color: #f8f8f8;
}
//去掉最上级的before  after 即是去电最上层的连接线
/deep/ .el-tree > div {
  &::before {
    display: none;
  }
  &::after {
    display: none;
  }
}
.max-size {
  width: 100% !important;
  max-width: 100% !important;
  padding-left: 16px !important;
}
</style>
